package mingkong

import (
	"encoding/base64"
	"encoding/binary"
	"fmt"
	"github.com/sigurn/crc16"
)

const (
	Head1 = 0xa5
	Head2 = 0x5a
	Tail1 = 0x55
	Tail2 = 0xaa
)

func Encode(seconds int) (packet string, fPort int) {
	var device []byte
	var n uint32
	fPort = 1
	n = uint32(seconds / 60) // 换算成分钟
	device = append(device, 0x00, 0x00, 0x00, 0x00)
	//device = append(device, 0x01, 0x6E, 0xAB, 0x33)

	//device = append(device, 0x39, 0x30, 0x35, 0x30)
	bs := setUploadInternal(device, n)
	fmt.Printf("%x\n", bs)
	packet = base64.StdEncoding.EncodeToString(bs)
	//tmp := fmt.Sprintf("%x", bs)
	//packet = base64.StdEncoding.EncodeToString([]byte(tmp))

	return
}
func setUploadInternal(device []byte, n uint32) (bs []byte) {

	var body []byte
	//body = append(body, 0x02, 0x04, 0x00, 0x00, 0x03, 0x6f)
	//body = append(body, 0x03, 0x04, 0x00, 0x00, 0x00, 0x91)
	param := int32Bytes(n)
	body = append(body, 0x05, 0x04)
	body = append(body, param...)

	bs = packet(device, body)
	return
}

func packet(device []byte, body []byte) (frame []byte) {

	frame = append(frame, Head1, Head2, 0xef, 0x00) // 包长度先记为0
	frame = append(frame, device...)

	frame = append(frame, body...)
	size := len(frame) + 4 // 长度位当前长度+crc(2)+tail(2)
	frame[3] = byte(size)  // 设置包长度
	c := crc(frame)
	frame = append(frame, c...)
	frame = append(frame, Tail1, Tail2)
	return
}

func crc(bs []byte) (c []byte) {
	c = append(c, 0x00, 0x00)
	table := crc16.MakeTable(crc16.CRC16_MODBUS) // 8005

	sum := crc16.Checksum(bs, table)
	binary.BigEndian.PutUint16(c, sum)
	return
}

func int16Bytes(n uint16) (bs []byte) {
	bs = append(bs, 0x00, 0x00)
	binary.BigEndian.PutUint16(bs, n)
	return
}

func int32Bytes(n uint32) (bs []byte) {
	bs = append(bs, 0x00, 0x00, 0x00, 0x00)
	binary.BigEndian.PutUint32(bs, n)
	return
}
